package com.lanhai.zhonglai.listener;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lanhai.zhonglai.dispatch.DispatchStation;


/**
 * 收取来自对接设备的消息
 *
 * @author virus408
 */
@Component
public class StationListener {
    @Autowired
    DispatchStation dispaD;


    private boolean running;
    private Thread th;

    public void Start(int port) {
        running = true;
        th = new Thread() {
            @Override
            public void run() {
                try {
                    DatagramSocket ds = new DatagramSocket(port);
                    while (running) {
                        byte buf[] = new byte[20];
                        DatagramPacket dp = new DatagramPacket(buf, buf.length);
                        ds.receive(dp);
                        dispaD.resolve(dp.getAddress().getHostAddress(), buf);
                        // dispaD.resolve("10.11.34.66", buf);
                    }
                    ds.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        };
        th.start();
    }


    public void Stop() {
        running = false;
        try {
            th.interrupt();
            th = null;
        } catch (Exception e) {
        }
    }
}
